package com.hmdp.service.impl;

import com.hmdp.controller.VoucherController;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.lang.annotation.Target;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //主线程代理对象 提取出来方便
    private IVoucherOrderService proxy;

    //将订单信息放到阻塞队列中
    /*private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    //创建单一线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //在bean加载完之后 利用线程池提交任务处理类
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //订单任务处理任务 内部类 实现runnable接口
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            //不断从阻塞队列中取出任务，获取订单的信息，
            while (true) {
                try {
                    VoucherOrder voucherorder = orderTasks.take();
                    //处理订单
                    handlerVoucherOrder(voucherorder);
                } catch (Exception e) {
                    log.info("处理订单异常，{}", e);
                }
            }
        }
    }

    //子线程处理订单
    private void handlerVoucherOrder(VoucherOrder voucherorder) {
        //子线程 threadLocal中的数据是主线程的不能用
        Long userId = voucherorder.getUserId();
        //获取锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        //获取锁失败，返回错误或重试
        if (!isLock) {
            log.error("不能重复下单");
            return;
        }

        try {
            //通过代理类调用来创建订单
            proxy.createVoucherOrder(voucherorder);
        } finally {
            //释放锁
            lock.unlock();
        }
    }*/

    //创建订单 其实不用判断了
    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder voucherorder) {
        Long userId = voucherorder.getUserId();

        //判断该用户是否下过单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherorder.getVoucherId()).count();
        if (count > 0) {
            log.error("不能重复下单");
        }

        //修改数据库
        boolean success = iSeckillVoucherService.update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherorder.getVoucherId()).gt("stock", 0)
                .update();
        /*boolean success2 = iSeckillVoucherService.lambdaUpdate().setSql("sock = stock - 1 ")
                .eq(SeckillVoucher::getVoucherId, voucherorder.getVoucherId())
                .gt(SeckillVoucher::getStock, 0).update();*/

        if (!success) {
            log.error("库存不足");
        }

        //保存订单到数据库
        save(voucherorder);
    }

    //秒杀订单判断
    @Transactional
    @Override
    public Result seckillVoucher(Long voucherId) {

        Long userId = UserHolder.getUser().getId();

        //执行秒杀判断脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),  //key集合
                voucherId.toString(), userId.toString()  //参数集合 可变参数
        );
        int res = result.intValue();
        //判断结果是否为0
        //不为0代表没有购买资格
        if (res != 0) {
            return Result.fail(res == 1 ? "库存不足" : "不能重复下单");
        }

        //为0代表有购买资格

        //获取主线程的代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        long orderId = redisIdWorker.nextId("order");
        //通过rabbitmq实现异步下单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        voucherOrder.setStatus(1);

        //将订单添加到阻塞队列中  异步下单写入数据库
        //orderTasks.add(voucherOrder);

        // 将订单信息发送到 RabbitMQ 队列
        rabbitTemplate.convertAndSend("seckill.order.exchange", "seckill.order.routingKey", voucherOrder);

        //有购买资格直接返回订单id，实现异步下单
        return Result.ok(orderId);
    }

    @Override
    public Result getResult(Long voucherId) {
        return null;
    }

    //未优化版
   /* @Override
    public Result seckillVoucher(Long voucherId) {
        //查数据库
        SeckillVoucher data = iSeckillVoucherService.getById(voucherId);

        //判断当前时间是否处于抢购时间
        if (LocalDateTime.now().isBefore(data.getBeginTime())) {
            return Result.fail("抢购尚未开始");
        }
        if (LocalDateTime.now().isAfter(data.getEndTime())) {
            return Result.fail("抢购已经开始");
        }

        //判断库存是否为0
        if (data.getStock() < 1) {
            return Result.fail("库存不足");
        }

        Long userId = UserHolder.getUser().getId();
        //获取锁对象
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);

        //尝试获取锁
        //boolean isLock = lock.tryLock(1200L);

        boolean isLock = lock.tryLock();
        //获取锁失败，返回错误或重试 这里是返回
        if (!isLock) {
            return Result.fail("一个用户只能抢购一次");
        }

            //return getResult(voucherId); 直接调用事务失效
            //拿到接口的代理对象
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.getResult(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    //乐观锁解决库存超卖问题 判断是否修改  CAS 或版本号法（解决ABA问题）
    @Transactional
    public Result getResult(Long voucherId) {

        Long userId = UserHolder.getUser().getId(); //因为每次都是一个对象，所有需要值一样intern

            //判断该用户是否下过单
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("抢购失败，一个用户只能抢购一次");
            }

            //修改数据库  乐观锁
            boolean success = iSeckillVoucherService.update().setSql("stock = stock - 1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if (!success) {
                return Result.fail("库存不足");
            }

            //创建订单
            //生成唯一id
            long orderId = redisIdWorker.nextId("order");
            VoucherOrder voucherOrder = new VoucherOrder();
            voucherOrder.setId(orderId);
            voucherOrder.setVoucherId(voucherId);
            voucherOrder.setUserId(userId);
            voucherOrder.setStatus(1);
            //保存订单到数据库
            save(voucherOrder);

            return Result.ok(orderId);
    }*/

}
